<template>
  <view class="app-layout">
    <app-header :title="tit" />
    <view class="app-main">
      <view class="feeding-form">
        <view class="add_btncon">
          <view class="tit">
            加料商品
          </view>
          <button class="submit_btn" @click="addClick" v-if="tit=='新增加料商品'">+ 新增</button>

        </view>
        <view class="" style=" flex: 1; overflow: hidden;">
          <scroll-view scroll-y="true" style="height: 100%">
            <uni-table border stripe emptyText="暂无更多数据">
              <uni-tr>
                <uni-th align="left" width="300"><text class="start">*</text>加料商品名称</uni-th>
                <uni-th align="left" width="100"><text class="start">*</text>售价（元）</uni-th>
                <uni-th align="left" width="100"><text class="start">*</text>库存（件）</uni-th>
                <uni-th align="left" width="100">状态</uni-th>
                <uni-th align="left" width="100">操作</uni-th>
              </uni-tr>
              <uni-tr v-for="(item, index) in tabList" :key="item">
                <uni-td>
                  <uni-easyinput placeholder="请输入" v-model="item.name" clearable :maxlength="30">
                    <template #right>
                      <text class="suffix-num">{{ (item.name || '').length }}/30</text>
                    </template>
                  </uni-easyinput>
                </uni-td>
                <uni-td>
                  <uni-easyinput placeholder="请输入" v-model="item.price" type="digit" clearable></uni-easyinput></uni-td>
                <uni-td>
                  <uni-easyinput placeholder="请输入" v-model="item.stock" type="number" clearable>
                  </uni-easyinput></uni-td>
                <uni-td>
                  <u-switch v-model="item.status" size="20" :activeValue="1" :inactiveValue="0"
                    activeColor="#20D048"></u-switch>
                </uni-td>
                <uni-td>
                  <view class="del-name" @click="removeClick(index)"> 删除 </view>
                </uni-td>
              </uni-tr>
            </uni-table>
          </scroll-view>
        </view>
        <view class="submit_btncon">
          <view style="display: flex; margin: auto">
            <button class="submit_close" @click="close">取消</button>
            <button class="submit_btn" @click="submit">确定</button>
          </view>
        </view>
      </view>

    </view>
  </view>
</template>
<script setup>
  import {
    ref
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    addAddonOptions,
    updateAddonOptions
  } from '@/requests/apis/products'
  let tit = ref('新增加料商品')
  let tabList = ref([])
  let categoryId = ref()
  onLoad((e) => {
    if (e.infoList) {
      tit.value = '编辑加料商品'
      let data = JSON.parse(decodeURIComponent(e.infoList))
      data.price = data.price + '';
      data.stock = data.stock + '';
      tabList.value.push(data)

    }
  })
  const addClick = () => {
    tabList.value.push({
      name: '',
      stock: undefined,
      status: 1,
      price: undefined,
    })
  }
  const removeClick = (index) => {
    tabList.value.splice(index, 1)
  }
  const close = () => {
    uni.navigateBack()
  }
  const submit = async () => {
    // 1. 检查是否有数据
    if (tabList.value.length === 0) {
      uni.showToast({
        title: '请至少添加一项加料商品',
        icon: 'none',
        duration: 2000,
      })
      return
    }

    // 匹配“非负整数”或“非负两位小数”的正则（核心：限制最多两位小数）
    const priceReg = /^\d+(\.\d{1,2})?$/;

    // 2. 检查每项的必填字段及格式（新增小数位数限制）
    for (let i = 0; i < tabList.value.length; i++) {
      const item = tabList.value[i];
      const rowNum = i + 1; // 行号，方便定位问题

      // 验证名称（原有逻辑保留）
      if (!item.name?.trim()) {
        uni.showToast({
          title: `第${rowNum}项：请填写加料商品名称`,
          icon: 'none',
          duration: 2000,
        })
        return
      }

      // -------------------------- 售价校验：非空 + 非负 + 最多两位小数 --------------------------
      const priceValue = item.price?.trim();
      // 2.1 非空校验
      if (!priceValue) {
        uni.showToast({
          title: `请填写售价`,
          icon: 'none',
          duration: 2000,
        })
        return
      }
      // 2.2 有效数字 + 非负校验
      const priceNum = Number(priceValue);
      if (isNaN(priceNum) || priceNum < 0) {
        uni.showToast({
          title: `售价必须为整数或两位小数`,
          icon: 'none',
          duration: 2000,
        })
        return
      }
      // 2.3 新增：最多两位小数校验（正则匹配）
      if (!priceReg.test(priceValue)) {
        uni.showToast({
          title: `售价必须为整数或两位小数`,
          icon: 'none',
          duration: 2000,
        })
        return
      }

      // -------------------------- 库存校验：非空 + 非负整数 --------------------------
      const stockValue = item.stock?.trim();
      // 2.4 非空校验
      if (!stockValue) {
        uni.showToast({
          title: `请填写库存数量`,
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      // 2.5 有效数字 + 非负 + 整数校验
      const stockNum = Number(stockValue);
      if (isNaN(stockNum) || stockNum < 0 || !Number.isInteger(stockNum)) {
        uni.showToast({
          title: `库存需为非负整数（不能为负数或小数）`,
          icon: 'none',
          duration: 2000,
        });
        return;
      }
    }

    // 3. 提交处理（补充：统一售价格式为两位小数，避免接口格式异常）
    uni.showLoading({
      title: '加载中...',
      mask: true
    })
    const fn = tit.value == '编辑加料商品' ? updateAddonOptions : addAddonOptions
    const formData = JSON.parse(JSON.stringify(tabList.value));
    formData.forEach(item => {
      // 售价：转为数字后保留两位小数（确保接口接收格式统一）
      item.price = item.price ? Number(Number(item.price).toFixed(2)) : null;
      // 库存：保留原有逻辑（去除非数字字符后转为数字）
      item.stock = item.stock ? Number(item.stock.replace(/\D/g, '')) : null;
    });
    const requestParams = tit.value == '编辑加料商品' ? {
      id: formData[0].id,
      status: formData[0].status,
      name: formData[0].name,
      stock: formData[0].stock,
      price: formData[0].price
    } : {
      addonForms: formData
    }

    try {
      const res = await fn(requestParams)
      if (res) {
        uni.showToast({
          title: res.Result || "",
          icon: 'success',
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 800)
      }
      uni.hideLoading()
    } catch (error) {
      console.log(error)
      uni.hideLoading()
    }
  }
</script>
<style lang="scss" scoped>
  .feeding-form {
    width: 100%;
    background: #ffffff;
    border-radius: 10px;
    margin: 10px 10px 0;
    padding: 26px 20px 0px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    :deep(.uni-table-scroll) {
      width: auto !important;
    }

    .suffix-num {
      font-weight: 400;
      font-size: 14px;
      color: rgba(51, 70, 129, 0.6);
      padding-right: 10px;
      box-sizing: border-box;
    }

    .del-name {
      font-weight: 400;
      font-size: 14px;
      color: #0F90FD;
    }

    .add_btncon {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      .tit {
        font-weight: 400;
        font-size: 14px;
        color: #333333;
        margin-right: 20px;
      }

      button {
        margin: 0;
        padding: 0 21px;
        box-sizing: border-box;
        border-radius: 100px;
        border: 1px solid #0f90fd;
        font-weight: 500;
        font-size: 14px;
        color: #309FFD;

        &:after {
          border: none;
        }
      }
    }

  }
</style>
